package hibernatemock.persistence;

import javax.persistence.EntityManager;

public class PrepareIds implements PropertyCallBack {

	private RecursiveSearch recursiveSearch = new RecursiveSearch(this);
	private EntityManager entityManager;

	public void prepare(Object rootEntity, EntityManager entityManager) {
		this.entityManager = entityManager;
		recursiveSearch.start(rootEntity);
	}

	@Override public void propertyCallBack(PropertyDescription propertyDescription) {
		if (propertyDescription.isAutoIncrementId()) {
			propertyDescription.setValue(null);
		} else if (propertyDescription.getId() != null) {
			String str = "select max(" + propertyDescription.getField().getName() + ") + 1 from "
					+ propertyDescription.getRootObject().getClass().getName();
			Object object = entityManager.createQuery(str).getSingleResult();
			if (object != null) {
				if (object instanceof Number) {
					Number number = (Number) object;
					propertyDescription.setValue(number);
				}
			}
		}
	}

}
